<template>
  <BaseDialog
    :visible="visible"
    title="录像播放器"
    width="90%"
    :footer-type="'close'"
    close-text="关闭"
    @update:visible="$emit('update:visible', $event)"
    @close="handleClose"
  >
    <div v-if="!record" class="no-selection">
      <el-icon class="no-selection-icon"><VideoCamera /></el-icon>
      <p>请选择要播放的录像</p>
    </div>
    
    <div v-else class="playback-dialog">
      <!-- 播放器信息 -->
      <div class="player-header">
        <div class="player-info">
          <h3>{{ record.cameraName }}</h3>
          <p>{{ record.startTime }} - {{ record.endTime }}</p>
          <div class="record-meta">
            <el-tag :type="getRecordTypeColor(record.type)" size="small">
              {{ getRecordTypeText(record.type) }}
            </el-tag>
            <span class="duration">{{ formatDuration(record.duration) }}</span>
            <span class="file-size">{{ formatFileSize(record.fileSize) }}</span>
          </div>
        </div>
        <div class="player-controls">
          <el-button @click="toggleFullscreen">
            <el-icon><FullScreen /></el-icon>
            全屏
          </el-button>
          <el-button @click="captureScreenshot">
            <el-icon><Picture /></el-icon>
            截图
          </el-button>
          <el-button @click="downloadRecord">
            <el-icon><Download /></el-icon>
            下载
          </el-button>
        </div>
      </div>
      
      <!-- 视频播放器 -->
      <div class="video-player">
        <VideoPlayer 
          :video-url="record.playUrl"
          :width="'100%'"
          :height="'500px'"
          :autoplay="false"
          :show-custom-controls="true"
          :poster="record.thumbnail"
        />
      </div>
      
      <!-- 播放控制 -->
      <div class="playback-controls">
        <div class="control-buttons">
          <el-button @click="togglePlayback" :type="isPlaying ? 'warning' : 'primary'">
            <el-icon>
              <VideoPause v-if="isPlaying" />
              <VideoPlay v-else />
            </el-icon>
            {{ isPlaying ? '暂停' : '播放' }}
          </el-button>
          <el-button @click="stopPlayback">
            <el-icon><CircleClose /></el-icon>
            停止
          </el-button>
          <el-button @click="seekBackward">
            <el-icon><ArrowLeft /></el-icon>
            快退10s
          </el-button>
          <el-button @click="seekForward">
            <el-icon><ArrowRight /></el-icon>
            快进10s
          </el-button>
        </div>
        
        <div class="time-display">
          <span>{{ formatTime(currentTime) }}</span>
          <span>/</span>
          <span>{{ formatTime(record.duration) }}</span>
        </div>
      </div>
      
      <!-- 时间轴控制 -->
      <div class="timeline-controls">
        <div class="timeline-header">
          <span>时间轴控制</span>
          <el-button-group size="small">
            <el-button @click="timelineZoom('in')">放大</el-button>
            <el-button @click="timelineZoom('out')">缩小</el-button>
            <el-button @click="timelineZoom('fit')">适应</el-button>
          </el-button-group>
        </div>
        
        <div class="timeline-container">
          <div class="timeline-ruler">
            <el-slider
              v-model="playbackPosition"
              :max="100"
              :step="0.1"
              :show-tooltip="true"
              :format-tooltip="formatTooltip"
              @change="seekToPosition"
            />
          </div>
        </div>
      </div>
    </div>
  </BaseDialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import {
  ElButton,
  ElIcon,
  ElTag,
  ElSlider,
  ElButtonGroup
} from 'element-plus'
import {
  VideoPause,
  VideoPlay,
  VideoCamera,
  FullScreen,
  Picture,
  Download,
  CircleClose,
  ArrowLeft,
  ArrowRight
} from '@element-plus/icons-vue'
import BaseDialog from '@/components/BaseDialog.vue'
import VideoPlayer from '@/components/VideoPlayer.vue'
import { success, info } from '@/utils/toast'
import type { PlaybackRecord } from '@/stores/playback'

// Props
interface Props {
  visible: boolean
  record: PlaybackRecord | null
  isPlaying: boolean
  playbackPosition: number
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  record: null,
  isPlaying: false,
  playbackPosition: 0
})

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'update:isPlaying': [value: boolean]
  'update:playbackPosition': [value: number]
  'seek': [position: number]
  'download': [record: PlaybackRecord]
  'close': []
}>()

// 响应式数据
const currentTime = ref(0)

// 计算属性
const playbackPosition = computed({
  get: () => props.playbackPosition,
  set: (value) => emit('update:playbackPosition', value)
})

// 方法
const handleClose = () => {
  emit('close')
  emit('update:visible', false)
}

const togglePlayback = () => {
  emit('update:isPlaying', !props.isPlaying)
}

const stopPlayback = () => {
  emit('update:isPlaying', false)
  emit('update:playbackPosition', 0)
  currentTime.value = 0
}

const seekBackward = () => {
  const newPosition = Math.max(0, props.playbackPosition - 10)
  emit('seek', newPosition)
}

const seekForward = () => {
  const newPosition = Math.min(100, props.playbackPosition + 10)
  emit('seek', newPosition)
}

const seekToPosition = (position: number | number[]) => {
  const pos = Array.isArray(position) ? position[0] : position
  if (props.record) {
    const timeInSeconds = (pos / 100) * props.record.duration
    currentTime.value = timeInSeconds
    emit('seek', pos)
  }
}

const toggleFullscreen = () => {
  info('切换全屏模式')
}

const captureScreenshot = () => {
  success('截图成功')
}

const downloadRecord = () => {
  if (props.record) {
    emit('download', props.record)
  }
}

const timelineZoom = (action: 'in' | 'out' | 'fit') => {
  const actions = {
    in: '放大',
    out: '缩小',
    fit: '适应'
  }
  info(`时间轴${actions[action]}`)
}

// 工具函数
const formatDuration = (seconds: number): string => {
  const hrs = Math.floor(seconds / 3600)
  const mins = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)
  
  if (hrs > 0) {
    return `${hrs.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const formatTime = (seconds: number): string => {
  return formatDuration(seconds)
}

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const getRecordTypeColor = (type: string): 'success' | 'primary' | 'warning' | 'info' | 'danger' => {
  const colors = {
    schedule: 'success' as const,
    manual: 'primary' as const,
    alarm: 'danger' as const
  }
  return colors[type as keyof typeof colors] || 'info'
}

const getRecordTypeText = (type: string) => {
  const texts = {
    schedule: '计划',
    manual: '手动',
    alarm: '告警'
  }
  return texts[type as keyof typeof texts] || '未知'
}

const formatTooltip = (value: number) => {
  if (props.record) {
    const timeInSeconds = (value / 100) * props.record.duration
    return formatDuration(timeInSeconds)
  }
  return '00:00'
}

// 监听播放状态变化
watch(() => props.isPlaying, (playing) => {
  if (playing && props.record) {
    // 模拟播放进度更新
    const interval = setInterval(() => {
      if (!props.isPlaying) {
        clearInterval(interval)
        return
      }
      
      currentTime.value += 1
      const newPosition = (currentTime.value / (props.record?.duration || 1)) * 100
      if (newPosition >= 100) {
        emit('update:isPlaying', false)
        clearInterval(interval)
      } else {
        emit('update:playbackPosition', newPosition)
      }
    }, 1000)
  }
})

// 监听录像变化
watch(() => props.record, (newRecord) => {
  if (newRecord) {
    currentTime.value = 0
    emit('update:playbackPosition', 0)
    emit('update:isPlaying', false)
  }
})
</script>

<style scoped>
.no-selection {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #909399;
}

.no-selection-icon {
  font-size: 64px;
  margin-bottom: 16px;
  color: #dcdfe6;
}

.playback-dialog {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 600px;
}

.player-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.player-info h3 {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 18px;
}

.player-info p {
  margin: 0 0 8px 0;
  color: #909399;
  font-size: 14px;
}

.record-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #606266;
}

.duration, .file-size {
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.player-controls {
  display: flex;
  gap: 8px;
}

.video-player {
  margin-bottom: 16px;
  border-radius: 8px;
  overflow: hidden;
  background: #000;
  flex: 1;
  min-height: 500px;
}

.playback-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.control-buttons {
  display: flex;
  gap: 8px;
}

.time-display {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #606266;
  font-family: monospace;
}

.timeline-controls {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.timeline-container {
  background: white;
  border-radius: 4px;
  padding: 12px;
  border: 1px solid #e4e7ed;
}

.timeline-ruler {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .player-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .player-controls {
    width: 100%;
    justify-content: flex-end;
  }
  
  .playback-controls {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .control-buttons {
    justify-content: center;
  }
  
  .timeline-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .video-player {
    min-height: 300px;
  }
}
</style>
